import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class StudentListFrame extends JFrame {
    private User teacher;
    private JTable studentTable;
    private DefaultTableModel tableModel;
    private JButton viewDetailButton;
    private JButton refreshButton;
    private JButton closeButton;
    private UserDAO userDAO;
    private ExamRecordDAO examRecordDAO;

    public StudentListFrame(User teacher) {
        this.teacher = teacher;
        this.userDAO = new UserDAO();
        this.examRecordDAO = new ExamRecordDAO();

        initComponents();
        setupLayout();
        setupEvents();
        loadStudentList();
    }

    private void initComponents() {
        setTitle("学生管理");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(800, 600);
        setLocationRelativeTo(null);

        // 表格列名
        String[] columnNames = { "学生ID", "用户名", "真实姓名", "邮箱", "手机号", "参与考试数", "平均分" };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        studentTable = new JTable(tableModel);
        studentTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        studentTable.setRowHeight(25);

        viewDetailButton = new JButton("查看详情");
        refreshButton = new JButton("刷新");
        closeButton = new JButton("关闭");
    }

    private void setupLayout() {
        setLayout(new BorderLayout());

        // 顶部面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(new Color(70, 130, 180));
        topPanel.setPreferredSize(new Dimension(800, 60));

        JLabel titleLabel = new JLabel("学生信息管理", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        titleLabel.setForeground(Color.WHITE);

        JPanel infoPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        infoPanel.setBackground(new Color(70, 130, 180));
        JLabel teacherLabel = new JLabel("教师: " + teacher.getRealName());
        teacherLabel.setForeground(Color.WHITE);
        infoPanel.add(teacherLabel);

        topPanel.add(titleLabel, BorderLayout.CENTER);
        topPanel.add(infoPanel, BorderLayout.EAST);

        // 中间表格面板
        JScrollPane scrollPane = new JScrollPane(studentTable);
        scrollPane.setBorder(BorderFactory.createTitledBorder("学生列表"));

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(viewDetailButton);
        buttonPanel.add(refreshButton);
        buttonPanel.add(closeButton);

        add(topPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void setupEvents() {
        viewDetailButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                viewStudentDetail();
            }
        });

        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loadStudentList();
            }
        });

        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        // 双击查看详情
        studentTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2) {
                    viewStudentDetail();
                }
            }
        });
    }

    private void loadStudentList() {
        tableModel.setRowCount(0);
        List<User> students = userDAO.getAllStudents();

        for (User student : students) {
            // 计算该学生的考试统计信息
            StudentStats stats = calculateStudentStats(student.getId());

            Object[] row = {
                    student.getId(),
                    student.getUsername(),
                    student.getRealName(),
                    student.getEmail() != null ? student.getEmail() : "",
                    student.getPhone() != null ? student.getPhone() : "",
                    stats.examCount,
                    stats.averageScore > 0 ? String.format("%.1f", stats.averageScore) : "无"
            };
            tableModel.addRow(row);
        }
    }

    private StudentStats calculateStudentStats(int studentId) {
        StudentStats stats = new StudentStats();

        // 这里应该查询该学生参与的所有考试记录
        // 为了简化，我们先返回默认值
        stats.examCount = 0;
        stats.averageScore = 0.0;

        // 实际实现中，应该查询exam_records表来计算统计信息
        // 这里省略具体实现

        return stats;
    }

    private void viewStudentDetail() {
        int selectedRow = studentTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择一个学生！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int studentId = (Integer) tableModel.getValueAt(selectedRow, 0);
        String studentName = (String) tableModel.getValueAt(selectedRow, 2);

        // 显示学生详细信息
        StringBuilder info = new StringBuilder();
        info.append("学生详细信息:\n\n");
        info.append("学生ID: ").append(studentId).append("\n");
        info.append("姓名: ").append(studentName).append("\n");
        info.append("用户名: ").append(tableModel.getValueAt(selectedRow, 1)).append("\n");
        info.append("邮箱: ").append(tableModel.getValueAt(selectedRow, 3)).append("\n");
        info.append("手机号: ").append(tableModel.getValueAt(selectedRow, 4)).append("\n");
        info.append("参与考试数: ").append(tableModel.getValueAt(selectedRow, 5)).append("\n");
        info.append("平均分: ").append(tableModel.getValueAt(selectedRow, 6)).append("\n");

        JOptionPane.showMessageDialog(this, info.toString(), "学生详情", JOptionPane.INFORMATION_MESSAGE);
    }

    // 内部类用于存储学生统计信息
    private static class StudentStats {
        int examCount;
        double averageScore;
    }
}